package com.uft.model.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.uft.model.entity.Profile;
import com.uft.model.entity.Server;
import com.uft.model.entity.ServerRuntime;
import com.uft.model.entity.ServerSettings;
import com.uft.was.connector.WasManagementListener;



@Repository
public class ServerDAO {
	
	@PersistenceContext private EntityManager em;
	private  static Logger  logger = Logger.getLogger(ServerDAO.class);
	 // Retrieves all the Profiles:
	   public List<Server> getAllServers(int startIndex, int pageSize) {
	       TypedQuery<Server> query = em.createQuery(
	           "SELECT s FROM Server s ", Server.class);
	       query.setFirstResult(startIndex);
	       query.setMaxResults(pageSize);
	       List<Server> servers=query.getResultList();
	       return servers;
	   }

	   public Server getServerById(int serverId){
		   System.out.println("Server id: "+serverId);
		   Server server = em.find(Server.class, serverId);
		   return server;
	   }
	   @SuppressWarnings("unchecked")
	   public List<Server> getServersByName(String serverName) {
		  return  em.createNamedQuery("getServerByName")
		    .setParameter("serverName", serverName)
		    .getResultList();
	   }
	   
	   @SuppressWarnings("unchecked")
	   public List<Server> getServerByNode(String nodeName) {
		  return  em.createNamedQuery("getServerByName")
		    .setParameter("nodeName", nodeName)
		    .getResultList();
	   }
	   @SuppressWarnings("unchecked")
	   public List<Server> getServerByServerHostname(String serverHostname) {
		  return  em.createNamedQuery("getServerByHost")
		    .setParameter("serverHostname", serverHostname)
		    .getResultList();
	   }
	   @SuppressWarnings("unchecked")
	   public List<Server> getServerByNameNodeHost(String serverName, String nodeName,String serverHostname) {
		  return  em.createNamedQuery("getServerByNameNodeHost")
		    .setParameter("serverName", serverName)
		    .setParameter("nodeName", nodeName)
		    .setParameter("serverHostname", serverHostname)
		    .getResultList();
	   }
	   @SuppressWarnings("unchecked")
	   public List<Server> getServerByNameNode(String serverName, String nodeName, int startIndex, int pageSize) {
		   String sql="SELECT s FROM Server s ";
		   if(serverName != null && nodeName!= null 
				   && !serverName.equalsIgnoreCase("") && !nodeName.equalsIgnoreCase("")){
			   sql+=" WHERE  s.serverName='"+serverName+"'"+ " and s.nodeName='"+nodeName+"'";
		   }else  if( serverName != null &&  !serverName.equalsIgnoreCase("")){
			   sql+=" WHERE  s.serverName='"+serverName+"'";
		   }else if( nodeName != null && !nodeName.equalsIgnoreCase("")){
			   sql+=" WHERE  s.nodeName='"+nodeName+"'";
		   }
		   TypedQuery<Server> query = em.createQuery(
				   sql, Server.class);
		   query.setFirstResult(startIndex);
	       query.setMaxResults(pageSize);
	       List<Server> servers=query.getResultList();
	       return servers;
	   }
	   public int getServerCount(){
		   String queryString = "SELECT Count(*) FROM Server";
		   Query query = em.createNativeQuery(queryString); 
		   return (Integer) query.getSingleResult();
	   }
	   
	   public 	List<String> searchServerByServerName(String searchString){
		   return  em.createNamedQuery("searchServerByServerName")
				    .setParameter("sString", "%"+searchString+"%")
				    .getResultList();
	   }
	   public 	List<String> searchServerByNodeName(String searchString){
		   return  em.createNamedQuery("searchServerByNodeName")
				    .setParameter("sString", "%"+searchString+"%")
				    .getResultList();
	   }
	   public List<String> searchServerByServerHostname(String searchString) {
		   return  em.createNamedQuery("searchServerByServerHostname")
				    .setParameter("sString", "%"+searchString+"%")
				    .getResultList();
		}
	   
	  
	   public List<Server> getAllServersByProfile(int profileId) {
	      ProfileDAO profileDAO= new ProfileDAO();
	      Profile profile=profileDAO.getProfileById(profileId);
	      List<Server> serverList=(List<Server>) profile.getServers();
	      return serverList;
	   }
	   
	   @Transactional
	   public void addNewServerByProfileId(String profileId, Server server){
		   System.out.println("Profile Id: "+profileId);
		   
		  // em.persist(server.getServerRuntime());
		  // em.persist(server.getServerSettings());
		   em.persist(server);
		   ServerRuntime serverRuntime= new ServerRuntime();
		   server.setServerRuntime(serverRuntime);
		   ServerSettings serverSettings= new ServerSettings();
		   server.setServerSettings(serverSettings);
		   em.flush();
		   Profile profile=em.find(Profile.class, Integer.valueOf(profileId));
		   profile.addServer(server);
		   em.merge(profile);
		  
		   System.out.println("Server Id: "+server.getServerId());
	   }
	    
	   @Transactional
	   public void deleteServerById(int serverId){
		   System.out.println("Server id: "+serverId);
		   Server server = em.find(Server.class, serverId);
		   em.remove(server);
	   }
	   @Transactional
		public void updateServer(Server server) {
			// TODO Auto-generated method stub
		   System.out.println("Server name: "+server.getServerName());
		   em.merge(server);
		   System.out.println("Server id: "+server.getServerId());
			
		}
	 @Transactional
	public void updateServerSetting(ServerSettings serverSettings) {
		// TODO Auto-generated method stub
		 System.out.println("Server Setting: "+serverSettings.getId());
		 em.merge(serverSettings);
		 System.out.println("Server Setting id: "+serverSettings.getId());
	}
	
	 @Transactional
	public void updateServerRuntime(ServerRuntime serverRuntime) {
		// TODO Auto-generated method stub
		 em.merge(serverRuntime);
		 logger.debug("Server Setting id: "+serverRuntime.getId());
	}
	 @Transactional
	public void updateServerStatus(String serverId, String result) {
		// TODO Auto-generated method stub
		logger.debug("Updating the server status: serverId "+serverId+" Result: "+result);
		Server server = em.find(Server.class, Integer.parseInt(serverId));
		server.getServerRuntime().setStatus(result);
		 em.merge(server);
		
	}
	   
	   
}
